package com.example.flowermall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.flowermall.entity.Role;
import com.example.flowermall.entity.RoleMenu;
import com.example.flowermall.mapper.RoleMapper;
import com.example.flowermall.mapper.RoleMenuMapper;
import com.example.flowermall.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoman
 * @since 2023-06-07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Override
    @Transactional
    public void addRole(Role role) {
        //写入角色表
        roleMapper.insert(role);
        //角色菜单关系表
        if(role.getMenuIdList()!=null){
            for(Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }

    @Override
    @Transactional
    public void delete(Integer roleId) {
        roleMapper.deleteById(roleId);
        LambdaQueryWrapper<RoleMenu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,roleId);
        roleMenuMapper.delete(queryWrapper);
    }

    @Override
    public Role select(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(roleId);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
        //修改角色表
        roleMapper.updateById(role);
        //删除角色权限
        LambdaQueryWrapper<RoleMenu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId,role.getRoleId());
        roleMenuMapper.delete(queryWrapper);
        //新增角色权限
        if(role.getMenuIdList()!=null){
            for(Integer menuId:role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }
}
